<?php
if(!$is_success){
    $dp = new jDatePicker();
    $dp->__dateFormat = "yy-mm-dd";
    echo "<scr"."ipt type=\"text/javascript\">";
    $dp->generateDP("tanggal_invoice");
    echo "</scr"."ipt>";
    $dp->init();
?>
<script type="text/javascript"> 
    jQuery.ajaxSetup({async: false});
    
    function _obj_fSendValue(kode, nama, elmKode, elmNama) {
            var elmk = document.getElementById("" + elmKode + "");
            var elmn = document.getElementById("" + elmNama + "");
            try {
                if(elmk.value == "")
                    elmk.value = kode;
                else
                    elmk.value = elmk.value + "," + kode;
                
                if(elmn.value == "")
                    elmn.value = nama;
                else
                    elmn.value = elmn.value + "\n" + nama;
                    
                    jQuery.ajax({
                        type: "POST",
                        url : "<?php echo site_url('popup/get_supplier_detil_2') ?>" ,
                        data: {kode: kode},
                        success: function(msg){
                            var result = jQuery.parseJSON(msg);
                            jQuery("#nama_supplier").val(result.nama_supplier);
                            jQuery("#id_supplier").val(result.id_supplier);
                            jQuery("#alamat_detail_supplier").val(result.alamat_detail_supplier);
                            jQuery("#alamat_komplit").val(result.alamat_komplit);
                            jQuery("#kontak_komplit").val(result.kontak_komplit);
                            jQuery("#attendance").val(result.attendance);
                        },
                        error: function(msg){
                            alert(msg);
                        }
                    });  
            }
            catch(e) {
                    alert(e.message);
            }
    }
    
    function init_item(quot){
        jQuery.ajax({
            type: "POST",
            url : "<?php echo site_url('popup/get_po_item') ?>",
            data: {quot: quot},
            success: function(msg){
                var result = jQuery.parseJSON(msg);
                
                for(var i = 0; i < result.length; i++)
                    append_table(result[i]);
            },
            error: function(msg){
                alert(msg);
            }
        });
    }
    
    function append_table(result){
        var length = jQuery("#tablebody").find("tr").length;
        
        if(length == 1){
            jQuery("#no_item").hide();
        }
        
        var index = -1, i = -1;
        var $ids = jQuery("input[name='id_item[]']");
        if($ids.length > 0){
            $ids.each(function(){
                if(this.value != result.item)
                    i++;
                else{
                    index = i + 1;
                    
                    var $qty = jQuery("input[name='quantity[]']").eq(index);
                    var $td = jQuery("#tablebody").find(".GridItem1").eq(index + 1).find("td");
                    
                    var new_qty = parseInt(result.qty) + parseInt($qty.val());
                    var total = parseFloat($td.eq(4).first().contents().filter(function(){
                        return this.nodeType == Node.TEXT_NODE;
                    }).text().replace(/[^\d]/,''));
                    var totald = parseFloat($td.eq(6).first().contents().filter(function(){
                        return this.nodeType == Node.TEXT_NODE;
                    }).text().replace(/[^\d]/,''));
                    
                    $qty.val(new_qty);
                    $td.eq(2).html(new_qty + ' ' + result.satuan);
                    $td.eq(4).html('<span style="float: left;">Rp. </span>' + formatNumber((parseFloat(total) + parseFloat(result.total))));
                    $td.eq(6).html('<span style="float: left;">$ </span>' + formatNumber((parseFloat(totald) + parseFloat(result.totald))));
                }
            });
        }
           
        if(index == -1)
            jQuery("#tablebody").append(
                '<tr class="GridItem1">\n'+
                    '<td>'+length+'<input type="hidden" name="quantity[]" value="'+result.qty+'" /><input type="hidden" name="id_item[]" value="'+result.item+'" /></td>\n'+
                    '<td>'+result.nama+'</td>\n'+
                    '<td>'+result.qty+' '+result.satuan+'</td>\n'+
                    '<td class="IDR" align="right"><span style="float: left;">Rp. </span>'+formatNumber(result.price)+'</td>\n'+
                    '<td class="IDR" align="right"><span style="float: left;">Rp. </span>'+formatNumber(result.total)+'</td>\n'+
                    '<td class="USD" align="right"><span style="float: left;">$ </span>'+formatNumber(result.priced)+'</td>\n'+
                    '<td class="USD" align="right"><span style="float: left;">$ </span>'+formatNumber(result.totald)+'</td>\n'+
                    '<td><input type=checkbox name=selected[] checked=checked value='+result.item+' onclick="update_price(this, this.checked);" /></td>'+
                '</tr>'
            );
            
        jQuery("#total").html(parseFloat(jQuery("#total").html()) + parseFloat(result.total));
        jQuery("#totald").html(parseFloat(jQuery("#totald").html()) + parseFloat(result.totald));
        
        updateCrcSymbol();
        ReFormat();
    }
    
    function ReFormat(){
        try{
            jQuery(".shou").each(function(){
                jQuery("#"+this.id+"_show").html(formatNumber(parseFloat(jQuery(this).html()), 2));
            });
        }catch(e){
            alert(e);
        }
    }
    
    function update_price(elm, checked){
        var tr_parent = jQuery(elm).parent().parent();
        var td_total = jQuery(tr_parent).find("td").toArray();
        var total_deleted = parseFloat(jQuery(td_total[4]).first().contents().filter(function(){
            return this.nodeType == Node.TEXT_NODE;
        }).text().replace(/[^\d]/,''));
        var totald_deleted = parseFloat(jQuery(td_total[6]).first().contents().filter(function(){
            return this.nodeType == Node.TEXT_NODE;
        }).text().replace(/[^\d]/,''));
        
        if(checked){
            jQuery("#total").html(parseFloat(jQuery("#total").html()) + parseFloat(total_deleted));
            jQuery("#totald").html(parseFloat(jQuery("#totald").html()) + parseFloat(totald_deleted));
            jQuery(tr_parent).addClass("GridItem1");
        } else {
            jQuery("#total").html(parseFloat(jQuery("#total").html()) - parseFloat(total_deleted));
            jQuery("#totald").html(parseFloat(jQuery("#totald").html()) - parseFloat(totald_deleted));
            jQuery(tr_parent).removeClass("GridItem1");
        }
        
        ReFormat();
    }
    
    function set_element(is_read_only){
        if(is_read_only){
            jQuery("#nama_supplier").addClass("read-only");
            jQuery("#alamat_detail_supplier").addClass("read-only");
            jQuery("#alamat_komplit").addClass("read-only");
            jQuery("#kontak_komplit").addClass("read-only");
            jQuery("#attendance").addClass("read-only");
        } else {
            jQuery("#nama_supplier").removeClass("read-only");
            jQuery("#alamat_detail_supplier").removeClass("read-only");
            jQuery("#alamat_komplit").removeClass("read-only");
            jQuery("#kontak_komplit").removeClass("read-only");
            jQuery("#attendance").removeClass("read-only");
            
            jQuery("#list_po_id").val("");
            jQuery("#list_quotation_number").val("");
            jQuery("#nama_supplier").val("");
            jQuery("#alamat_detail_supplier").val("");
            jQuery("#alamat_komplit").val("");
            jQuery("#kontak_komplit").val("");
            jQuery("#attendance").val("");
            jQuery("#id_supplier").val("");
            
            jQuery("#tablebody").find("tr").each(function(){
                if(this.id != "no_item")
                    jQuery(this).remove();
            });
            
            jQuery("#no_item").show();
            jQuery("#total").html(0);
        }
        
        jQuery("#nama_supplier").attr("readonly", is_read_only);
        jQuery("#alamat_detail_supplier").attr("readonly", is_read_only);
        jQuery("#alamat_komplit").attr("readonly", is_read_only);
        jQuery("#kontak_komplit").attr("readonly", is_read_only);
        jQuery("#attendance").attr("readonly", is_read_only);
    }
    
    function setBlnToRome(bln){
        if(bln=="01"){
            return "I";
        }else if(bln=="02"){
            return "II";
        }else if(bln=="03"){
            return "III";
        }else if(bln=="04"){
            return "IV";
        }else if(bln=="05"){
            return "V";
        }else if(bln=="06"){
            return "VI";
        }else if(bln=="07"){
            return "VII";
        }else if(bln=="08"){
            return "VIII";
        }else if(bln=="09"){
            return "IX";
        }else if(bln=="10"){
            return "X";
        }else if(bln=="11"){
            return "XI";
        }else{
            return "XII";
        }
    }
    
    function setPurchaseNumber(){
         var prefix = <?php echo json_encode($prefix); ?>;

         var date = (jQuery("#tanggal_invoice").val()).toString();
         var partsArray = date.split('-');
         var tgl = partsArray[2];
         var bln = setBlnToRome(partsArray[1]);
         var thn =  partsArray[0];
         var no= prefix + "/ASP/PO/" + tgl +"/" + bln +"/" +thn;
         jQuery("#nomor_po").val(no);
         
    }
    
    function updateCrcSymbol(){
        var symbol = jQuery("#curency").val();
        if(symbol=="IDR") {
            jQuery(".IDR").show();
            jQuery(".USD").hide();
        }else{
            jQuery(".IDR").hide();
            jQuery(".USD").show();
        }  
    }
    
    function append_diskon(val){
        jQuery("#diskon").val(parseInt(jQuery("#diskon").val()) + parseInt(val));
    }
    
    function close_gb(){
        <?php echo CloseGB(true); // close greybox   ?>
    }
    
    function download_item(file){
        window.open('<?php echo base_url("import");?>/'+file, '_blank');
    }
    
    function formatNumber (obj, decimal) {
        //decimal  - the number of decimals after the digit from 0 to 3
        //-- Returns the passed number as a string in the xxx,xxx.xx format.
        anynum = eval(obj);
        divider =10;
        switch(decimal){
            case 0:
                divider =1;
                break;
            case 1:
                divider =10;
                break;
            case 2:
                divider =100;
                break;
            default:       //for 3 decimal places
                divider =1000;
        }

        workNum=Math.abs((Math.round(anynum*divider)/divider));
        workStr=""+workNum
        if (workStr.indexOf(",")==-1){workStr+=","}
        dStr=workStr.substr(0,workStr.indexOf(","));
        dNum=dStr-0
        pStr=workStr.substr(workStr.indexOf(","))

        while (pStr.length-1< decimal){
            pStr+="0"
        }

        if(pStr ==',') pStr ='';
        //--- Adds a comma in the thousands place.
        if (dNum>=1000) {
            dLen=dStr.length
            dStr=parseInt(""+(dNum/1000))+"."+dStr.substring(dLen-3,dLen)
        }
        //-- Adds a comma in the millions place.
        if (dNum>=1000000) {
            dLen=dStr.length
            dStr=parseInt(""+(dNum/1000000))+"."+dStr.substring(dLen-7,dLen)
        }

        retval = dStr + pStr
        //-- Put numbers in parentheses if negative.
        if (anynum<0) {retval="("+retval+")";}
        //You could include a dollar sign in the return value.
        //retval =  "$"+retval
        return retval;
    }
</script>
<style>
    .shou{
        display: none;
    }
</style>

<h3 class="title-popup">Form Tambah Invoice</h3>

<div style="padding:10px">
    
    <?php if ($error != "") { ?>
        <div class="BoxMessage Warning">Proses Gagal, <br /><?php echo $error; ?></div>
    <?php } ?>
    
<div id="content">
<div class="DivTable">
<?php 
    echo form_open_multipart();
    
    $list_po_number = array();
    $list_po_id = array();
    
    if(is_object($list_po)){
        foreach ($list_po->result() as $row) {
            $list_po_id[] = $row->id_po;
            $list_po_number[] = $row->nomor_po;
        }
    }
    
    $list_po_id = implode(",", $list_po_id);
    $list_po_number = implode("\n", $list_po_number);
?>
<table>
    <tr>
        <td>Date</td>
        <td>:</td>
        <td><?php echo form_input(array("name" => "tanggal_invoice", "id" => "tanggal_invoice", "class" => "input_text", "readonly" => "readonly", "size" => 47), $tanggal_invoice);?></td>
        <td>&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>File Invoice</td>
        <td>:</td>
        <td>
            <?php 
                echo form_input(array("name" => "file_upload", "id" => "file_upload", "type" => "file", "class" => "input_file", "size" => 10));
                echo "&nbsp;";
                if(!empty($file_attachment_invoice)){
                    echo '<a href="#" onclick="download_item(\''.$file_attachment_invoice.'\')" title="download"><img src="'.  base_url("style/layout/images/icons/arrow_down.png").'"/>Download</a>';
                }
            ?>
        </td>    
    </tr>  
    <tr>
        <td>PO Number</td>
        <td>:</td>
        <td>
            <?php echo form_textarea(array("name" => "list_po_number", "id" => "list_po_number", "rows"=>2,"cols"=>37, "readonly"=>"readonly", "class"=>"read-only"), $list_po_number);?>
            <input type="hidden" name="list_po_id" id="list_po_id" value="<?php echo $list_po_id;?>"   />
        </td>
        <td>
            <?php echo $gbquote ?>
            <a class="clear" onclick="set_element(false);" title="Clear Choice"><span></span></a>
            <a class="help" onclick="alert('Berisi daftar nomor quotation. Dipisahkan oleh tanda enter');" title="Dapatkan supplier"><span></span></a>
        </td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>Invoice Note</td>
        <td>:</td>
        <td><?php echo form_textarea(array("name" => "catatan_invoice", "id" => "catatan_invoice", "class" => "input_text", "rows"=>2,"cols"=>37  ),$catatan_invoice);?></td>
    </tr> 
    <tr>
        <td>Requester</td>
        <td>:</td>
        <td>
            <input type="text" name="nama_supplier" id="nama_supplier" value="<?php echo $nama_supplier;?>" maxlength="50" size="50" />
            <input type="hidden" name="id_supplier" id="id_supplier" value="<?php echo $id_supplier;?>"   />
        </td>
        <td>&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>Invoice NO</td>
        <td>:</td>
        <td><?php echo form_input(array("name" => "nomor_invoice", "id" => "nomor_invoice", "size" => "50"),$nomor_invoice);?></td>
    </tr>
    <tr>
        <td>Address</td>
        <td>:</td>
        <td><?php echo form_input(array("name" => "alamat_detail_supplier", "id" => "alamat_detail_supplier", "size" => 50),$alamat_detail_supplier);?></td>
    </tr>
    <tr>
        <td>Full Address</td>
        <td>:</td>
        <td>
            <?php echo form_textarea(array("name" => "alamat_komplit", "id" => "alamat_komplit", "class" => "input_text", "rows"=>2,"cols"=>37  ),$alamat_komplit);?>
        </td>
        <td>
            <a class="help" onclick="alert('Berisi alamat lengkap, kota, kodepos. Dipisahkan oleh tanda enter');" title="Petunjuk"><span></span></a>
        </td>
    </tr>
    <tr>
        <td>Phone/Fax/Email</td>
        <td>:</td>
        <td>
            <?php echo form_input(array("name" => "kontak_komplit", "id" => "kontak_komplit", "class" => "input_text", "size"=>50  ),$kontak_komplit);?>
        </td>
        <td>
            <a class="help" onclick="alert('Berisi no telepon, fax, dan email. Dipisahkan oleh tanda /');" title="Petunjuk"><span></span></a>
        </td>
    </tr>
    <tr>
        <td>Currency</td>
        <td>:</td>
        <td>
            <?php 
                if ($using_dollar_currency == 1){
                    $crc = "USD";
                } else {
                    $crc = "IDR";
                }
            ?>
            <select id="curency" name="crc" onchange="updateCrcSymbol()" value="<?php echo $crc;?>">
                        <option value="<?php echo $crc;?>"><?php echo $crc;?></option>                        
                        <option value="USD">USD</option>
                        <option value="IDR">IDR</option>                        
            </select>
        </td>
        <td>&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>Diskon</td>
        <td>:</td>
        <td><?php echo form_input(array("name" => "diskon", "id" => "diskon", "size"=>50), $diskon, "onkeyup=\"this.value=this.value.replace(/[^\d]/,'');\"");?></td>
    </tr>   
</table>
<br/>

<?php echo $gbitem; ?>

<br/><br/>

<table class="GridTable" style="width: 100%;">
    <thead>
        <tr class="GridHeader">
            <td>No.</td>
            <td>Description</td>
            <td>Qty</td>
            <td class="IDR">Unit Price</td>
            <td class="IDR">Total Price</td>
            <td class="USD">Unit Price Dollar</td>
            <td class="USD">Total Price Dollar</td>
            <td width="5%">Action</td>
        </tr>
    </thead>
    <tbody id="tablebody">
        <tr class="GridItem1" id="no_item">
            <td colspan="8">Tidak ada data</td>
        </tr>
        <?php 
            $total_harga = 0;
            $totald_harga = 0;
            if(is_object($item)){
            if($item->num_rows() > 0) {
                $nomor = 1;
                foreach($item->result() as $row){
        ?>
                <tr class="GridItem1">
                    <td><?php echo $nomor++;?></td>
                    <td><input type="hidden" name="quantity[]" value="<?php echo $row->quantity?>" /><?php echo $row->nama_item?><input type="hidden" name="id_item[]" value="<?php echo $row->id_item?>" /></td>
                    <td><?php echo $row->quantity . " " . $row->satuan_beli?></td>
                    <td class="IDR" align="right"><span style="float: left;">Rp. </span><?php echo number_format($row->harga_jual, 0, ',', '.')?></td>
                    <td class="IDR" align="right"><span style="float: left;">Rp. </span><?php echo number_format($row->harga_jual * $row->quantity, 0, ',', '.')?></td>
                    <td class="USD" align="right"><span style="float: left;">$ </span><?php echo number_format($row->harga_jual_dollar, 0, ',', '.')?></td>
                    <td class="USD" align="right"><span style="float: left;">$ </span><?php echo number_format($row->harga_jual_dollar * $row->quantity, 0, ',', '.')?></td>
                    <td><input type=checkbox name=selected[] checked=checked value='<?php echo $row->id_item?>' onclick="update_price(this, this.checked);" /></td>
                </tr>
        <?php 
                    $total_harga += $row->harga_jual * $row->quantity;
                    $totald_harga += $row->harga_jual_dollar * $row->quantity;
                }

                echo "<script>jQuery(\"#no_item\").hide();</script>";
            } 
            }
        ?>
    </tbody>
    <tfoot>
        <tr class="GridHeader">
            <td colspan="3" align="right">Total</td>
            <td class="IDR">&nbsp;</td>
            <td class="IDR" align="right"><span style="float: left;">Rp. </span><span id="total" class='shou'><?php echo $total_harga?></span><span id="total_show">0</span></td>
            <td class="USD">&nbsp;</td>
            <td class="USD" align="right"><span style="float: left;">$ </span><span id="totald" class='shou'><?php echo $totald_harga?></span><span id="totald_show">0</span></td>
            <td>&nbsp;</td>
            <script>updateCrcSymbol();ReFormat();</script>
        </tr>
    </tfoot>
</table> 
<br/><br/>

<?=form_submit(array("name" => "btnSubmit","class"=>"CommandButton"), "Save")?>
<?=form_button(array("class"=>"CommandButton"), "Cancel", "onclick='close_gb();'")?>
<?=form_close()?>

</div>
</div>
</div>
<?php } else { ?>
<script type='text/javascript'>
    function close_gb(){
        <?php echo CloseGB(true); // close greybox   ?>
    }
</script>

<div style="padding-top: 25%;">
<div class="BoxMessage">Data Berhasil disimpan<br /><?php echo $error; ?></div>

<div id="box-control-save">    
     <?=form_button(array("class"=>"CommandButton"), "OK", "onclick='close_gb();'")?>
</div>
</div>
<?php } ?>